<?php

namespace app\admin\controller\wechat;

use app\common\controller\Backend;

use think\Controller;
use think\Request;

/**
 * 微信会员卡
 *
 * @icon fa fa-circle-o
 */
class Membercard extends Backend
{

    /**
     * WechatMemberCard模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('WechatMemberCard');
//        $this->cardModel = model('WechatCard');
        $this->view->assign("dateTypeList", $this->model->getDateTypeList());
        $this->view->assign("useCustomCodeList", $this->model->getUseCustomCodeList());
        $this->view->assign("getCustomCodeModeList", $this->model->getGetCustomCodeModeList());
        $this->view->assign("canGiveFriendList", $this->model->getCanGiveFriendList());
        $this->view->assign("needPushOnViewList", $this->model->getNeedPushOnViewList());
        $this->view->assign("codeTypeList", $this->model->getCodeTypeList());
        $this->view->assign("customNameTypeList", $this->model->getCustomNameTypeList());
        $this->view->assign("colorList", model('WechatCard')->getColorList());
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($this->dataLimit)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                // 应用数据限制
                if ($this->appletLimit)
                {
                    $params['appletid'] = $this->appletLimit;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false)
                    {
                        $card = $this->model->get($this->model->id);
                        $wechatCard = new \app\mpbase\library\WechatCard();
                        $result = $wechatCard->createCard('MEMBER_CARD', $card->getBaseInfo(), $card->getEspecial());
                        if($result['errcode'] == 0 && $result['errmsg'] == 'ok'){
                            $card->card_id = $result['card_id'];
                            $card->allowField(true)->save();
                            $this->error('Debug ING.');
//                              $this->success();
                        }else{
                            $card->delete();
                            $this->error($result);
                        }
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
//                catch (\EasyWeChat\Core\Exceptions\HttpException $e)
//                {
//                    $this->error($e->getMessage());
//                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if ($ids)
        {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds))
            {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v)
            {
                $wechatCard = new \app\mpbase\library\WechatCard();
                $result = $wechatCard->delete($v['card_id']);
                if($result['errcode'] == 0 && $result['errmsg'] == 'ok')
                $count += $v->delete();
            }
            if ($count)
            {
                $this->success();
            }
            else
            {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function setForm($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
//        $row = $this->model->where('id',$ids)->field('service_statement,bind_old_card,required_form,optional_form')->find()->toArray();
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                try{
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false){
                        $wechatCard = new \app\mpbase\library\WechatCard();
                        $requiredForm = $row->required_form;
                        $optionalForm = $row->optional_form;
                        $result = $wechatCard->activateUserForm($row->card_id, $requiredForm, $optionalForm);
                        $this->error('Debug..');
//                        $this->success();
                    }else{
                        $this->error($row->getError());
                    }
                }catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
